//
//  LoginViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/12/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import ReactiveCocoa

class LoginViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var accountField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    @IBOutlet weak var loginButton: UIButton!
    
    override func viewDidLoad() {
        combineLatest(accountField.rac_textSignalProducer(), passwordField.rac_textSignalProducer())
            .map { $0.0.characters.count > 0 && $0.1.characters.count > 0 }
            .start { self.loginButton.enabled = $0.value! }
        
        accountField.delegate = self
        passwordField.delegate = self
    }
    
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        if textField === accountField {
            passwordField.becomeFirstResponder()
            return false
        } else {
            self.login()
            return true
        }
    }
    
    @IBAction func login() {
        Alamofire.request(.POST, API.login, parameters: ["email": accountField.text!, "password": passwordField.text!])
            .responseJSON { response in
                
                if response.result.isSuccess {
                    let json = JSON(response.result.value!)
                    
                    if let message = json["message"].string {
                        print(message)
                        
                        return;
                    }
                    
                    let user = User(json)
                    
                    AccountManager.updateUser(user)
                    
                    let rootVC: UITabBarController = UIApplication.sharedApplication().keyWindow?.rootViewController as! UITabBarController
                    rootVC.selectedIndex = 1
                    
                    self.dismissViewControllerAnimated(true, completion: {})
                } else {
            
                }
        }
    }
    
    
    
    
}
